<?php
Namespace Cyfy\Modules\Forms;

use \Cyfy\Message;

/**
 * Creates a new fieldset element.
 *
 * Usage:
 * <code>
 * // called in method structure() of a form, that's why there is $this
 *
 * $f = new Forms\FieldSet('fieldset01','My great field set.');
 *
 * $i = new Forms\TextBox('username', 'Username');
 * $i -> required = true;
 * $i -> maxLength = 50;
 * $f -> addItem($i);
 *
 * $this -> addItem($f);
 * 
 * // some other items can be added directly
 * $i = new Forms\TextBox('aText', 'Some kind of a textbox');
 * $this -> addItem($i);
 *
 * </code>
 *
 * @author Dandelion <dandelion8888@gmail.com>
 * @version 0.1
 */
class FieldSet extends Input
{
    /**
     * Objects, which the fieldset contains.
     * @var array
     */
    private $contents = array();
    
    /**
     * Creates a new fieldset.
     * @param string Fieldset codename.
     * @param string Title of the fieldset.
     */
    function __construct($name, $title = "")
    {
        $this -> name = $name;
        $this -> title = $title;
    }
    
    /**
     * Adds an item into buffer.
     * @param object Instance of class derived from \Cyfy\Modules\Forms\Input
     */
    public function addItem($object)
    {
        $object -> inFieldset = true;
        $this -> contents[$object->name] = $object;
    }
    
    /**
     * Returns its contents.
     * @return array
     */
    public function getContents()
    {
        return $this -> contents;        
    }
    
    /**
     * Fills the object with custom data.
     * @param array Associative array in format array("elementName" => "value", "element2name" => "another value");
     */
    final function setData($data)
    {
        foreach($this -> contents as $object)
        {
            foreach($data as $name => $value)
            {
                if($object -> name == $name)
                {
                    $object -> value = $value;
                }
            }
        }
    }
    
    /**
     * Returns serialized fieldset.
     * @return string HTML code.
     */
    function __toString()
    {
        $output = "<fieldset>" . (($this -> title) ? "<legend>{$this->title}</legend>" : "");
        // inputs
        foreach($this -> contents as $object)
        {
            $output .= $object -> __toString();
        
        }
        $output .= "</fieldset>";
        return $output;
    }

}